﻿using Heyu.Utility;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.SessionState;

namespace TestSwfUpload
{
    /// <summary>
    /// upload1 的摘要说明
    /// </summary>
    public class upload1 : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            System.Drawing.Image thumbnail_image = null;

            try
            {
                //保存图片
                HttpPostedFile postfile = context.Request.Files["Filedata"];

                string path = context.Server.MapPath("~/uploads/images/product/temp");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                string filename = Guid.NewGuid().ToString();
                string spath = Path.Combine(path, filename + ".jpg");
                postfile.SaveAs(spath);

                //生成缩略图,并将图片转成byte
                thumbnail_image = ImageUtility.MakeThumbnail(spath, 100, 100, "Fill");
                byte[] buffer = ImageUtility.GetPictureData(thumbnail_image);

                SwfUploadModel thumb = new SwfUploadModel(filename, buffer);

                List<SwfUploadModel> thumbnails = context.Session["FileInfo"] as List<SwfUploadModel>;
                if (thumbnails == null)
                {
                    thumbnails = new List<SwfUploadModel>();
                    context.Session["FileInfo"] = thumbnails;
                }
                thumbnails.Add(thumb);

                context.Response.StatusCode = 200;
                context.Response.Write(filename);
            }
            catch
            {
                context.Response.StatusCode = 500;
                context.Response.Write("图片上传失败");
                context.Response.End();
            }
            finally
            {
                if (thumbnail_image != null) thumbnail_image.Dispose();
                context.Response.End();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}